// Mock 数据服务 - 用于开发阶段
import type { Project, Stats } from '../../types'
import type { DataSource, SyncLog, DataSourceStats } from '../services/dataIntegration'

// 模拟延迟
const delay = (ms: number = 500) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟项目数据
const mockProjects: Project[] = [
  {
    id: 1,
    project_code: 'SEO-ABC-2024-01',
    customer_name: 'ABC科技公司',
    customer_domain: 'abc-tech.com',
    project_type: 'SEO',
    status: '未开始',
    contract_terms: {
      text: 'ABC科技SEO优化服务合同',
      amount: 8000
    },
    start_date: '2024-01-20',
    end_date: '2024-12-20',
    customer_manager: '张经理',
    created_time: '2024-01-15T10:00:00Z',
    updated_time: '2024-01-15T10:00:00Z',
    contract_amount: 8000,
    contract_count: 1,
    items: [
      {
        id: 687,
        name: '综合外链',
        quantity: null,
        price: 2000,
        details: { as: null, da: 45, count: null, dofollow: false },
        status: 'PENDING'
      }
    ]
  },
  {
    id: 2,
    project_code: 'SEO-DEF-2023-12',
    customer_name: 'DEF金融集团',
    customer_domain: 'def-finance.com',
    project_type: 'SEO',
    status: '未达标',
    contract_terms: {
      text: 'DEF金融集团SEO优化服务合同',
      amount: 12000
    },
    start_date: '2023-12-01',
    end_date: '2024-12-01',
    customer_manager: '王经理',
    created_time: '2023-11-25T10:00:00Z',
    updated_time: '2024-01-15T10:00:00Z',
    contract_amount: 12000,
    contract_count: 2,
    items: [
      {
        id: 687,
        name: 'PR通稿',
        quantity: null,
        price: 200,
        details: { as: null, da: null, count: null, dofollow: false },
        status: 'PENDING'
      },
      {
        id: 688,
        name: '综合外链',
        quantity: 50,
        price: 1500,
        details: { as: null, da: 35, count: 50, dofollow: true },
        status: 'COMPLETED'
      }
    ]
  },
  {
    id: 3,
    project_code: 'SEO-JKL-2023-08',
    customer_name: 'JKL企业集团',
    customer_domain: 'jkl-corp.com',
    project_type: 'SEO',
    status: '已达标',
    contract_terms: '',
    start_date: '2023-12-28',
    end_date: '2024-06-28',
    customer_manager: '李经理',
    created_time: '2023-12-20T10:00:00Z',
    updated_time: '2024-06-28T10:00:00Z',
    contract_amount: 6500,
    contract_count: 2,
    items: [
      {
        id: 689,
        name: '综合外链',
        quantity: 100,
        price: 3000,
        details: { as: null, da: 55, count: 100, dofollow: true },
        status: 'COMPLETED'
      },
      {
        id: 690,
        name: 'PR通稿',
        quantity: 5,
        price: 1000,
        details: { as: null, da: null, count: 5, dofollow: false },
        status: 'COMPLETED'
      }
    ]
  },
  {
    id: 4,
    project_code: 'SEO-XYZ-2024-01',
    customer_name: 'XYZ电商平台',
    customer_domain: 'xyz-mall.com',
    project_type: 'BACKLINK_PACKAGE',
    status: '未开始',
    contract_terms: {
      text: 'XYZ电商平台外链建设服务合同',
      amount: 15000
    },
    start_date: '2024-01-25',
    end_date: '2024-07-25',
    customer_manager: '刘经理',
    created_time: '2024-01-20T10:00:00Z',
    updated_time: '2024-01-20T10:00:00Z',
    contract_amount: 15000,
    contract_count: 1,
    items: [
      {
        id: 691,
        name: '综合外链',
        quantity: 200,
        price: 5000,
        details: { as: null, da: 60, count: 200, dofollow: true },
        status: 'PENDING'
      }
    ]
  },
  {
    id: 5,
    project_code: 'SEO-GHI-2024-01',
    customer_name: 'GHI汽车公司',
    customer_domain: 'ghi-auto.com',
    project_type: 'BACKLINK_PREPAID',
    status: '未达标',
    contract_terms: {
      text: 'GHI汽车公司SEO推广服务合同',
      amount: 9800
    },
    start_date: '2024-01-01',
    end_date: '2024-06-30',
    customer_manager: '陈经理',
    created_time: '2023-12-25T10:00:00Z',
    updated_time: '2024-01-15T10:00:00Z',
    contract_amount: 9800,
    contract_count: 2,
    items: [
      {
        id: 692,
        name: 'PR通稿',
        quantity: 3,
        price: 600,
        details: { as: null, da: null, count: 3, dofollow: false },
        status: 'COMPLETED'
      },
      {
        id: 693,
        name: '综合外链',
        quantity: 80,
        price: 2400,
        details: { as: null, da: 40, count: 80, dofollow: true },
        status: 'PENDING'
      }
    ]
  }
]

// 模拟数据源数据
const mockDataSources: DataSource[] = [
  {
    id: 'auto',
    type: 'auto',
    name: '自动化外链系统',
    description: '直连数据库，实时同步',
    status: 'connected',
    config: {
      host: '192.168.1.10',
      port: 3306,
      database: 'auto_links',
      syncMode: '实时同步'
    },
    stats: {
      todayAdded: 1245,
      todayFailed: 18,
      totalRecords: 45678,
      lastSyncTime: new Date().toISOString()
    },
    connectionDetails: {
      latency: '2ms'
    }
  },
  {
    id: 'ugc',
    type: 'ugc',
    name: 'UGC内容发布系统',
    description: '直连数据库，实时同步',
    status: 'connected',
    config: {
      host: '192.168.1.11',
      port: 3306,
      database: 'ugc_content',
      syncMode: '实时同步'
    },
    stats: {
      todayAdded: 367,
      todayFailed: 14,
      totalRecords: 23456,
      lastSyncTime: new Date(Date.now() - 30000).toISOString()
    },
    connectionDetails: {
      latency: '5ms'
    }
  },
  {
    id: 'manual',
    type: 'manual',
    name: '人工采购系统',
    description: 'Excel模板导入，定期同步',
    status: 'connected',
    config: {
      importMethod: 'Excel模板',
      frequency: '每4小时'
    },
    stats: {
      todayAdded: 89,
      todayFailed: 13,
      totalRecords: 12345,
      lastSyncTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
    },
    connectionDetails: {
      nextSync: '16:00'
    }
  },
  {
    id: 'pr',
    type: 'pr',
    name: 'PR发布系统',
    description: '手动录入，定期同步',
    status: 'connected',
    config: {
      importMethod: '手动+批量',
      frequency: '每30分钟'
    },
    stats: {
      todayAdded: 45,
      todayFailed: 0,
      totalRecords: 8765,
      lastSyncTime: new Date(Date.now() - 2 * 60 * 1000).toISOString()
    },
    connectionDetails: {
      nextSync: '15:00'
    }
  }
]

// Mock API 服务
export const mockApi = {
  // 项目相关
  projects: {
    async getList(params?: any) {
      await delay()
      let filteredProjects = [...mockProjects]
      
      if (params?.vika_status && params.vika_status !== 'all') {
        filteredProjects = filteredProjects.filter(p => p.status === params.vika_status)
      }
      
      if (params?.keyword) {
        const keyword = params.keyword.toLowerCase()
        filteredProjects = filteredProjects.filter(p => 
          p.customer_name.toLowerCase().includes(keyword) ||
          p.customer_domain.toLowerCase().includes(keyword) ||
          p.project_code.toLowerCase().includes(keyword)
        )
      }
      
      return {
        code: 200,
        success: true,
        message: '获取成功',
        data: {
          list: filteredProjects,
          total: filteredProjects.length,
          page: params?.page || 1,
          pageSize: params?.pageSize || 10
        }
      }
    },

    async getDetail(id: number) {
      await delay()
      const project = mockProjects.find(p => p.id === id)
      if (!project) {
        return {
          code: 404,
          success: false,
          message: '项目不存在',
          data: null
        }
      }
      return {
        code: 200,
        success: true,
        message: '获取成功',
        data: project
      }
    },

    async getStats() {
      await delay()
      const stats: Stats = {
        total: mockProjects.length,
        未达标: mockProjects.filter(p => p.status === '未达标').length,
        已达标: mockProjects.filter(p => p.status === '已达标').length,
        未开始: mockProjects.filter(p => p.status === '未开始').length
      }
      return {
        code: 200,
        success: true,
        message: '获取成功',
        data: stats
      }
    }
  },

  // 进度相关
  progress: {
    async getProjectTimeline(projectId: number) {
      await delay()
      return {
        code: 200,
        success: true,
        message: 'Project timeline analysis retrieved successfully',
        data: [
          {
            date: '2025-07-30',
            progress: {
              'PR通稿': { completion_rate: 0.0, quality_rate: null },
              '综合外链': { completion_rate: 3.71, quality_rate: 0.0 },
              '金额使用': { completion_rate: 0.0, quality_rate: null }
            }
          },
          {
            date: '2025-07-31',
            progress: {
              'PR通稿': { completion_rate: 0.0, quality_rate: null },
              '综合外链': { completion_rate: 3.74, quality_rate: 0.0 },
              '金额使用': { completion_rate: 0.0, quality_rate: null }
            }
          }
        ]
      }
    }
  },

  // 数据整合相关
  dataIntegration: {
    async getSources() {
      await delay()
      return {
        code: 200,
        success: true,
        message: '获取成功',
        data: mockDataSources
      }
    },

    async syncData(type: string) {
      await delay(1000)
      return {
        code: 200,
        success: true,
        message: '同步成功',
        data: {
          taskId: `task_${Date.now()}`,
          message: `${type} 数据同步已开始`,
          estimatedTime: 30
        }
      }
    },

    async testConnection(type: string) {
      await delay(2000)
      const isSuccess = Math.random() > 0.3 // 70% 成功率
      return {
        code: 200,
        success: true,
        message: '测试完成',
        data: {
          success: isSuccess,
          latency: Math.floor(Math.random() * 50) + 10,
          message: isSuccess ? '连接正常' : '连接失败',
          details: {
            network: isSuccess,
            authentication: isSuccess,
            database: isSuccess,
            permissions: isSuccess
          }
        }
      }
    },

    async getStats() {
      await delay()
      const stats: DataSourceStats = {
        totalSources: mockDataSources.length,
        connectedSources: mockDataSources.filter(s => s.status === 'connected').length,
        todaySync: mockDataSources.reduce((sum, s) => sum + s.stats.todayAdded, 0),
        todayErrors: mockDataSources.reduce((sum, s) => sum + s.stats.todayFailed, 0),
        totalRecords: mockDataSources.reduce((sum, s) => sum + s.stats.totalRecords, 0)
      }
      return {
        code: 200,
        success: true,
        message: '获取成功',
        data: stats
      }
    }
  }
}

// 是否启用 Mock 模式
export const isMockMode = import.meta.env.VITE_MOCK_API === 'true' || import.meta.env.DEV